<?php

!defined('IN_NOVA') && exit('Access Denied!');

class User {

	private $user;

	public function __construct() {
		// 初始化为游客
		$this->user = array(
			// ID
			'uid'        => 0,
			// 用户名
			'username'   => '',
			// 用户组
			'group'      => 0,
			// 邮箱
			'email'      => '',
			// 登录 IP
			'ip'         => Request::get_ip(),
			// 注册时间
			'registime'  => 0,
			// 最后登录时间
			'logintime'  => PHP_TIME,
			// 最后活动时间
			'actiontime' => PHP_TIME,
			// 最后发帖时间
			'posttime'   => 0,
			// 最后搜索时间
			'searchtime' => 0,
		);
	}

    function __set( $name, $value ) {
        $this->set( $name, $value );
    }

    function __get( $name ) {
        return $this->get( $name );
    }

	// 增加或修改一个变量
    public function set( $index, $value ) {
		$this->user[$index] = $value;
    }

    // 获取一个变量
	public function get( $index ) {
		//[DEBUG]
		global $log;
		//[/DEBUG]
		if( !isset( $this->user[$index] ) ) {
			//[DEBUG]
			if( defined( 'APP_DEBUG' ) && APP_DEBUG === TRUE ) {
				$log->add( '[' . __FILE__ . '] [' . __LINE__ . '] ' . L( '_USE_ILLEGAL_INDEX_' ) . ' ' . $index, E_USER_NOTICE );
			}
			//[/DEBUG]
			return NULL;
		}
		return $this->user[$index];
	}


	// 用户登录
	// 返回值：0 用户名或密码为空，-1 用户不存在，-2 密码错误
	public function login( $username, $password, $remember = 0 ) {
		global $db;
		if ( $username == '' || $password == '' ) {
			return 0;
		}

		$result = $db->fetch_one_array( "SELECT * FROM `" . DB_PREFIX . "user` WHERE u_username = '$username'" );
		if ( !$result ) {
			return -1;
		}
		if ( $result['u_password'] != strtolower( md5( APP_PREFIX . $password ) ) && $result['u_password'] != $password ) {
			return -2;
		}

		$this->user['uid']        = $result['u_id'];
		$this->user['username']   = $result['u_username'];
		$this->user['group']      = $result['u_group'];
		$this->user['email']      = $result['u_email'];
		$this->user['actiontime'] = PHP_TIME;

		// 自动登录时可能不希望操作 COOKIE
		if( $remember != -1 ) {
			$expire = $remember ? PHP_TIME + ( 365 * 24 * 3600 ) : 0;
			$app_path = str_replace( ' ','%20', APP_PATH );
			setcookie( APP_PREFIX . 'username', $result['u_username'], $expire, $app_path );
			setcookie( APP_PREFIX . 'password', $result['u_password'], $expire, $app_path );
		}

		$db->query( "UPDATE `" . DB_PREFIX . "user` SET u_ip = '" . $this->user['ip'] . "',u_time = '" . PHP_TIME . "' WHERE u_id = " . $this->user['uid'] );
		return 1;
	}

	//用户登出
	public function logout() {
		$app_path = str_replace( ' ','%20', APP_PATH );
		setcookie( APP_PREFIX . 'username', NULL, 0, $app_path );
		setcookie( APP_PREFIX . 'password', NULL, 0, $app_path );
		return 1;
	}

	// 判断是否登录
	public function is_login() {
		if( $this->group > 0 ){
			return true;
		}else{
			return false;
		}
	}

	// 判断是否有前台管理权限
	public function is_admin() {
		if(  $this->group > 7 ){
			return true;
		}else{
			return false;
		}
	}

	// 判断是否有后台管理权限
	public function is_super_admin() {
		global $cache;
		if(  $this->group > 7 && $cache->config['enable'] == 0 ) return true;
		if (  $this->group > 7 && $_SESSION['user_group'] == 10 ) return true;
		return false;
	}

	//检查用户名是否合法
	//返回值：0 长度不合法，-1 包含非法字符，-2 包含禁用关键字
	public function check_username( $username, $check_filter = true ) {
		global $cache;
		// 长度检查
		if ( strlen( $username ) < 3 || strlen( $username ) > 20 ) {
			return 0;
		}
		// 检查非法字符
		$badchars = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','$','(',')','%','@','+','?',';','^');
		foreach ($badchars as $cha) {
			if (strpos($username,$cha) !== false) {
				return -1;
			}
		}
		if( $check_filter ) {
			// 检查禁用关键字
			$banname = split( "\|", $cache->config['namefilter'] );
			if ( count( $banname ) ) {
				foreach ( $banname as $val ) {
					if ( empty( $val ) ) continue;
					if ( !( strpos( strtolower( $username ), strtolower( $val ) ) === false) ) {
						return -2;
					}
				}
			}
		}
		return 1;
	}

	// 判断是否为合法密码
	//返回值：0 长度不合法，-1 包含非法字符
	public function check_password( $passwd ) {
		// 长度检查
		if ( strlen( $passwd ) < 5 || strlen( $passwd ) > 20 ) {
			return 0;
		}
		//特殊字符检测
		if( !ereg("^[_a-zA-Z0-9]*$",$passwd) ) return -1;
		return 1;
	}

	//验证email是否合法
	public function check_email($email) {
		if ( preg_match('/^[0-9a-z]+[0-9a-z_\.\-]*@[0-9a-z\-]+(\.[a-z]{2,4}){1,2}$/i', $email ) ) {
			return true;
		}
		return false;
	}

	// 判断是否为有效网址
	public function check_index( $weburl ) {
		if(!ereg("^http://[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*$",$weburl)) {
			return false;
		}
		return true;
	}
	
	// 刷新在线人数
	/*public function online() {
		global $cache,$db;
		if( $this->online != NULL ) {
			return $this->online;
		}

		$now_time = PHP_TIME; 
		$now_online = array();
		$user_login = FALSE;
		$user_name = $this->user['username'];
		// 在线有效时间，单位：秒 (即1200等于20分钟)
		$online_time = 1200;
		// 访问者 ip
		$user_ip = $this->user['ip'];

		if( defined( 'CACHE_ENABLE' ) && CACHE_ENABLE === TRUE && CACHE_TYPE != 'VOID' ) {
			if( $cache->online != NULL ) {
				// 得到仍然有效的数据
				foreach( $cache->online as $row => $value ) {
					if( ( $now_time - $value['time'] ) <= $online_time ) {
						$now_online[$value['ip']]['username'] = $value['username'];
						$now_online[$value['ip']]['time']     = $value['time'];
						$now_online[$value['ip']]['ip']     = $value['ip'];
						if( $value['ip'] == $user_ip ){
							$user_login = TRUE;
						}
					}
				}
			}

			// 更新状态
			$now_online[$user_ip]['username'] = $user_name;
			$now_online[$user_ip]['time']     = $now_time;
			$now_online[$user_ip]['ip']       = $user_ip;
			if( !$user_login ) {
				// 初次访问
				$db->query( "UPDATE `" . DB_PREFIX . "set` SET visitnum = visitnum + 1,todaynum = todaynum  + 1" );
			}
			$online_num = count( $now_online );
			$cache->set( 'online', $now_online, $timeout = 0 );
		} else {
			$online = array();
			$online = $db->fetch_all( 'SELECT * FROM `' . DB_PREFIX . 'online`' );

			// 得到仍然有效的数据
			foreach( $online as $row => $value ) {
				if( ( $now_time - $value['time'] ) <= $online_time ) {
					$now_online[$row]['username']  = $value['username'];
					$now_online[$row]['ip']   = $value['ip'];
					$now_online[$row]['time'] = $value['time'];
					if( $value['ip'] == $user_ip ){
						$user_login = true;
					}
				} else {
					$db->query( "DELETE FROM `" . DB_PREFIX . "online` WHERE ip = '" . $value['ip'] . "'" );
				}
			}

			$online_num = count( $now_online );

			if( $user_login ) {
				// 更新状态
				$db->query( "UPDATE `" . DB_PREFIX . "online` SET time=$now_time,username='$user_name' WHERE ip = '$user_ip'" );
			} else {
				// 初次访问
				$db->query( "INSERT INTO `" . DB_PREFIX . "online` (`username`,`ip`,`time`) VALUES ('$user_name','$user_ip',$now_time)" );
				$db->query( "UPDATE `" . DB_PREFIX . "set` SET visitnum = visitnum + 1,todaynum = todaynum  + 1" );
				$online_num ++;
			}
		}
		$this->online = $online_num;
		return $online_num;
	}*/

	// ----------------------------------------
	// 以下是私有函数
}

?>
